import java.util.*;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;



public class EDMail{
	
	private static String MAIL_MODE = null;
	private static String PRIVATE_KEY = null;
	
	public static void log(String m){
		if (m == null) return;
		System.out.println(m);
	}
	
	public static void init(String modefile, String privateKey)throws Exception{
		
		if (MAIL_MODE != null)return;
			
		if ( null == modefile || modefile.length()==0 ){
			throw new Exception("modefile value is wrong!!");
		}
		if ( null == privateKey || privateKey.length()==0 ){
			throw new Exception("privateKey value is wrong!!");
		}
		
		File mf = new File(modefile);
		
		if (!mf.isFile()){
			throw new Exception(modefile + " not exist or can not be opened");
		}
		BufferedReader reader = null;
		try{
			reader = new BufferedReader( new FileReader(mf));
			String line;
			while((line=reader.readLine())!=null){
				MAIL_MODE+=line+"\n";
			}
		} catch (Exception ex) {
			MAIL_MODE = null;	
			throw ex;
		} finally {
			if (reader != null) reader.close();
			
		}
		PRIVATE_KEY = privateKey;
	}
	

	public static String getEDMail(String uid, String nickname, String bindemail)throws Exception{
		if ( null == uid || uid.length()==0 ){
			throw new Exception("invalid uid value");
		}
		if ( null == nickname || nickname.length()==0 ){
			throw new Exception("invalid nickname value");
		}
		
		
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		String timestamp = String.valueOf(System.currentTimeMillis());
		byte[] authbyte = (PRIVATE_KEY + uid + timestamp + bindemail).getBytes("gbk");
		String authcode  = bytesToString(md5.digest(authbyte));
		
		StringBuilder strbd = new StringBuilder();  
		Formatter formatter = new Formatter(strbd); 
		formatter.format(MAIL_MODE, nickname, uid, timestamp, authcode, uid);         
		return strbd.toString();
	}
	
	public static String bytesToString(byte[] data) {  
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',  
                'e', 'f'};  
        char[] temp = new char[data.length * 2];  
        for (int i = 0; i < data.length; i++) {  
            byte b = data[i];  
            temp[i * 2] = hexDigits[b >>> 4 & 0x0f];  
            temp[i * 2 + 1] = hexDigits[b & 0x0f];  
        }  
        return new String(temp);  
  
    }  
	public static void main(String[] args){
				
		try{
			EDMail.init("mailmod.html", "privatekeyedm"); 
			String mailcont = EDMail.getEDMail("fengshihao@chianren.com", "fengshihao", "fengshihao@sohu.com");
			EDMail.log(mailcont);
		} catch (Exception ex){ 
		    ex.printStackTrace();
		}
		
	}
}